package com.cy.dda.web.admin.cases;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.comm.utils.ExportExcelUtils;
import com.cy.dda.model.PageBean;
import com.cy.dda.model.Result;
import com.cy.dda.model.ao.cases.CasesApplyEndAO;
import com.cy.dda.model.ao.cases.CasesEditAO;
import com.cy.dda.model.dto.cases.CasesImportDTO;
import com.cy.dda.model.enums.MessageType;
import com.cy.dda.model.query.cases.CasesAdminQuery;
import com.cy.dda.model.vo.cases.CasesAdminVO;
import com.cy.dda.model.vo.cases.CasesDetailInfoAdminVO;
import com.cy.dda.service.cases.CasesService;
import com.cy.dda.service.message.MessageService;
import com.cy.dda.web.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * 后台-委案管理
 *
 * @author: tanyilin
 * @create: 2018年11月1日 下午2:40:18
 */
@Slf4j
@RestController
@RequestMapping("/admin/cases")
@Api(tags = "后台-委案管理")
public class AdminCasesController extends BaseController {

	@Autowired
	private CasesService casesService;
	@Autowired
	private MessageService messageService;
	
	@ApiOperation("导入委案")
    @PostMapping("/import/excel")
	public Result improtExcel(@ApiParam(value = "委案Excel表格", required = true) @RequestParam MultipartFile file){
		//解析Excel表格数据
		List<CasesImportDTO> casesImportList = casesService.getCasesImportDTO(file);
		if(CommonUtils.isEmpty(casesImportList)) {
			return fail("表格数据为空");
		}
		//添加委案
		casesService.addCases(casesImportList);
		return ok("导入委案成功", casesImportList);
	}
	
	@ApiOperation("一键派单")
    @PostMapping("/do/distribute")
	public Result doDistribute(@ApiParam(value = "委案ID字符串casesIds") @RequestParam(required = false) String casesIds) {
		Result<List<Long>> result = casesService.distributeCasesBatch(casesIds);
		List<Long> casesIdsList = result.getData();
		casesIdsList.stream().forEach(id -> {
			messageService.sendMessage(id.toString(), MessageType.CASES_STATUS_NOTIFICATION);
		});
		return ok();
	}
	
	@ApiOperation("重新分配")
    @PostMapping("/do/redistribution")
	public Result doRedistribution(@RequestParam Long casesId) {
		casesService.redistributionCases(casesId);
		messageService.sendMessage(casesId.toString(), MessageType.CASES_STATUS_NOTIFICATION);
		return ok();
	}
	
	@ApiOperation("指定分配")
    @PostMapping("/do/appoint/distribute")
	public Result appointDistribute(@RequestParam Long casesId, @RequestParam Long userId) {
		casesService.appointDistributeCases(casesId, userId);
		messageService.sendMessage(casesId.toString(), MessageType.CASES_STATUS_NOTIFICATION);
		return ok();
	}
	
	@ApiOperation("未结束委案列表")
	@GetMapping("/unend/list")
	public PageBean<CasesAdminVO> selectUnEndCasesList(CasesAdminQuery query) {
		query.setFlag(1);
		PageBean<CasesAdminVO> pageBean = casesService.selectCasesAdminList(query);
		return pageBean;
	}
	
	@ApiOperation("导出未结束委案列表")
	@GetMapping("/unend/list/export")
	public void unendListExport(CasesAdminQuery query, HttpServletRequest req, HttpServletResponse resp) {
		query.setPage(1);
		query.setLimit(5000);
		List<CasesAdminVO> data = this.selectUnEndCasesList(query).getData();
		String title = "未结束委案列表";
		String[] headers = {"类型", "委案机构", "客户", "贷款产品", "贷款金额", "工作城市", "逾期时长", 
				"剩余追偿", "已回款", "催收记录", "催收员", "派单时间", "更新时间", "委案到期", "委案状态"};
		String[] fieldNames = {"casesTypeText", "orgName", "customerName", "productName", "loanAmount", "city", "overdueDays", 
				"surplusAmount", "repayAmount", "collectionRecordCount", "collectionUserName", "distributeTime", "updateTime", "entrustExpireDate", "casesStatusText"};
		ExportExcelUtils<CasesAdminVO> ex = new ExportExcelUtils<>();
		try(OutputStream out = resp.getOutputStream()) {
			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/x-download");
			String fileName = CommonUtils.getCurrentTimeAndRandomNumber().concat(".xls");
			fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
			resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			ex.exportExcel(title, headers, fieldNames, data, out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@ApiOperation("待结束委案列表")
	@GetMapping("/endwait/list")
	public PageBean<CasesAdminVO> selectEndWaitCasesList(CasesAdminQuery query) {
		query.setFlag(2);
		PageBean<CasesAdminVO> pageBean = casesService.selectCasesAdminList(query);
		return pageBean;
	}
	
	@ApiOperation("已结束委案列表")
	@GetMapping("/end/list")
	public PageBean<CasesAdminVO> selectEndCasesList(CasesAdminQuery query) {
		query.setFlag(3);
		PageBean<CasesAdminVO> pageBean = casesService.selectCasesAdminList(query);
		return pageBean;
	}
	
	@ApiOperation("导出已结束委案列表")
	@GetMapping("/end/list/export")
	public void endListExport(CasesAdminQuery query, HttpServletRequest req, HttpServletResponse resp) {
		query.setPage(1);
		query.setLimit(5000);
		List<CasesAdminVO> data = this.selectEndCasesList(query).getData();
		String title = "已结束委案列表";
		String[] headers = {"类型", "委案机构", "客户", "贷款产品", "贷款金额", "工作城市", "逾期时长", 
				"剩余追偿", "已回款", "催收记录", "催收员", "派单时间", "更新时间", "委案到期", "结束类型"};
		String[] fieldNames = {"casesTypeText", "orgName", "customerName", "productName", "loanAmount", "city", "overdueDays", 
				"surplusAmount", "repayAmount", "collectionRecordCount", "collectionUserName", "distributeTime", "updateTime", "entrustExpireDate", "casesEndTypeText"};
		ExportExcelUtils<CasesAdminVO> ex = new ExportExcelUtils<CasesAdminVO>();
		try(OutputStream out = resp.getOutputStream()) {
			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/x-download");
			String fileName = CommonUtils.getCurrentTimeAndRandomNumber().concat(".xls");
			fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
			resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			ex.exportExcel(title, headers, fieldNames, data, out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@ApiOperation("客户的委案列表")
	@GetMapping("/customer/list")
	public PageBean<CasesAdminVO> selectCustomerList(CasesAdminQuery query) {
		state(!CommonUtils.isEmpty(query.getCustomerId()), "客户ID不可为空");
		query.setFlag(null);
		PageBean<CasesAdminVO> pageBean = casesService.selectCasesAdminList(query);
		return pageBean;
	}
	
	@ApiOperation("催收员用户的委案列表")
	@GetMapping("/user/list")
	public PageBean<CasesAdminVO> selectUserList(CasesAdminQuery query) {
		state(!CommonUtils.isEmpty(query.getUserId()), "催收员用户ID不可为空");
		query.setFlag(null);
		PageBean<CasesAdminVO> pageBean = casesService.selectCasesAdminList(query);
		return pageBean;
	}
	
	@ApiOperation("委案信息详情")
	@GetMapping("/get/detail/info")
	public Result<CasesDetailInfoAdminVO> getDetailInfo(@RequestParam Long casesId) {
		CasesDetailInfoAdminVO modelVo = casesService.selectCasesDetailInfoAdminVO(casesId);
		return ok("查询成功", modelVo);
	}
	
	@ApiOperation("后台-确认结束委案")
	@PostMapping("/do/confirm/end")
	public Result toConfirmEndCases(@RequestParam(required = true) Long casesId) {
		casesService.toConfirmEndCases(casesId);
		messageService.sendMessage(casesId.toString(), MessageType.CASES_STATUS_NOTIFICATION);
		return ok();
	}
	
	@ApiOperation("后台-退回结束委案")
	@PostMapping("/do/return/end")
	public Result toReturnEndCases(@RequestParam(required = true) Long casesId) {
		casesService.updateCasesStatusFromEndWaitToProcessing(casesId);
		return ok();
	}
	
	@ApiOperation("委案编辑-信息详情")
	@GetMapping("/get/edit/info")
	public Result<CasesDetailInfoAdminVO> getEditInfo(@RequestParam Long casesId) {
		CasesDetailInfoAdminVO resultVo = casesService.selectCasesEditInfoAdmin(casesId);
		return ok("查询成功", resultVo);
	}
	
	@ApiOperation("确认编辑委案信息")
	@PostMapping("/do/edit")
	public Result doEdit(@Validated @RequestBody CasesEditAO editAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		casesService.doEditCases(editAO);
		return ok();
	}
	
	@ApiOperation("委案申请结案")
	@PostMapping("/apply/end")
	public Result applyEnd(@Validated CasesApplyEndAO casesApplyEndAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		casesService.applyEnd(casesApplyEndAO);
		return ok();
	}
	
	
}
